var util = require('../../../utils/util.js');
const db = wx.cloud.database();
//获取应用实例
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    type:"",//news|resource
    title:"",
    summary:"",
    content:"",
    files:[],
    fileIds:[],
    headFiles:[],
    headFileIds:[]
  },

  //输入监听
  bindInputValue(event) {
    let name = event.currentTarget.dataset.name;
    let max = event.currentTarget.dataset.max;
    let value = event.detail.value;

    //判断是否超过200个字符
    if (value && value.length > max) {
      return;
    }
    

    if ('title' == name) {
      this.setData({
        title: event.detail.value,
      });
    } else if ('summary' == name) {
      this.setData({
        summary: event.detail.value,
      });
    } else {
      this.setData({
        content: event.detail.value,
      });
    }
  },


  //选择图片(头部图片)
  chooseHeadImage: function (e) {
    var that = this;
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: function (res) {
        that.setData({
          headFiles: that.data.headFiles.concat(res.tempFilePaths)
        });
        that.uploadCloud("head", that.data.headFiles);
      }
    })
  },

  //选择资源图片
  chooseImage: function (e) {
    if (this.data.files.length > 3) {
      util.showErrorToast('只能上传3张图片')
      return false;
    }

    var that = this;
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: function (res) {
        that.setData({
          files: that.data.files.concat(res.tempFilePaths)
        });

        that.uploadCloud("content", res.tempFilePaths);
      }
    })
  },

  //上传图片(上传到云)
  uploadCloud: function (type,files) {
    var that = this;
    //临时目录
    const filePath = files[0];

    //文件扩展名
    var extName = filePath.match(/\.[^.]+?$/)[0];
    var currentTime = util.getCurrentTimeStr("yyyyMMddhhmmssS");
    var cloudPath = "upload/"+this.data.type+"/"+type+"/" + currentTime + Math.random() * 1000 + extName;

    wx.showLoading({
      title: '上传中',
    });

    wx.cloud.uploadFile({
      cloudPath,
      filePath,
      success: res => {

        if ("content"==type)
        {
          that.setData({
            fileIds: that.data.fileIds.concat(res.fileID)
          });
        }
        if ("head" == type) {
          that.setData({
            headFileIds: that.data.headFileIds.concat(res.fileID)
          });
        }
        //that.savePost([]);
      },
      fail: e => {
        console.error('[上传文件] 失败：', e)
        wx.showToast({
          icon: 'none',
          title: '上传失败',
        })
      },
      complete: () => {
        wx.hideLoading()
      }
    });
  },


  //发表贴子
  publishPost: function (e) {

    //如果已经登陆,且还没有记录
    if (!this.logged && e.detail.userInfo) {
      this.setData({
        logged: true,
        userInfo: e.detail.userInfo
      });
      app.globalData.userInfo = e.detail.userInfo;
    }

    if (null == this.data.userInfo) {
      util.showErrorToast("匿名不能发贴");
      return;
    }

    let that = this;
    if (!this.data.title || "" == this.data.title) {
      util.showErrorToast('请填写标题')
      return false;
    }
    if (!this.data.summary || "" == this.data.summary) {
      util.showErrorToast('请填写简介')
      return false;
    }
    this.savePost();
  },

  //保存贴子
  savePost: function (imgs) {
    var resourceType = this.data.type;
    var dbName = "home_resource";
    if ("news" == resourceType) {
      if (null == this.data.headFiles || 0 == this.data.headFiles.length)
      {
        wx.showToast({ title: '请上传头部图片'})
        return false;
      }

      dbName = "home_news";
    }

    var newResource = {
      "_openid": app.globalData._openid,
      "headImg": this.data.headFileIds,
      "imgs": this.data.fileIds,
      "showBanner": false,
      "title": this.data.title,
      "summary": this.data.summary,
      "content": this.data.content,
      "visit_count": 0,
      "reply_count": 0
    };
    var that = this;
        
    db.collection(dbName).add({
      data: newResource,
      success: res => {
        wx.showToast({
          title: '发表成功'
        });
        wx.navigateBack({
          delta: 1
        });
      },
      fail: e => {
        wx.showToast({
          title: '发布错误',
        });
      }
    })
  },

  //预览图片
  previewImage: function (e) {
    var name = e.currentTarget.url;
    let tempFiles = null;
    if(name == 'img')
    {
      tempFiles = this.data.files;
    }else{
      tempFiles = this.data.headFiles;
    }
    
    wx.previewImage({
      current: e.currentTarget.url, // 当前显示图片的http链接
      urls: tempFiles // 需要预览的图片http链接列表
    })
  },

  //重置贴子
  resetPublish: function () {
    this.setData({
      title: "",
      summary: "",
      content: "",
      files: [],
      fileIds: [],
      headFileIds: [],
      headFiles: []
    });
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    //设置资源类型为  (资源or资讯)
    var topicType = options.type;
    this.setData({ type: topicType});
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})